package tr.edu.metu.is550.isell.security.spring;

import com.google.code.springcryptoutils.core.cipher.asymmetric.Base64EncodedCipherer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("isellAuthenticationFilter")
public class ISellAuthenticationFilter extends GenericFilterBean {
    private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();

    @Autowired
    @Qualifier("org.springframework.security.authenticationManager")
    private AuthenticationManager authenticationManager;

    @Autowired
    private Base64EncodedCipherer decrypter;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final boolean debug = logger.isDebugEnabled();
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;

        String header = request.getHeader("Authorization");

        if (header == null || !header.startsWith("ISell ")) {
            chain.doFilter(req, res);
            return;
        }

        try {

            String[] tokens = extractHeader(header);
            String username = tokens[0];

            if (debug) {
                logger.debug("Authentication Authorization header found for user '" + username + "'");
            }

            if (!authenticationIsRequired(username))
                chain.doFilter(req, res);

            UsernamePasswordAuthenticationToken authRequest =
                    new UsernamePasswordAuthenticationToken(username, tokens[1]);

            authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
            Authentication authResult = authenticationManager.authenticate(authRequest);

            if (debug) {
                logger.debug("Authentication success: " + authResult);
            }

            SecurityContextHolder.getContext().setAuthentication(authResult);
            chain.doFilter(request, response);
        } catch (AuthenticationException e) {
            SecurityContextHolder.clearContext();
            if (debug) {
                logger.debug("Authentication request for failed: " + e);
            }
            chain.doFilter(request, response);
        }


    }

    private boolean authenticationIsRequired(String username) {
        return true;
    }

    private String[] extractHeader(String header) throws IOException {

        String token;

        try {
            token = decrypter.encrypt(header.substring(6));
        } catch (Exception e) {
            logger.info(e);
            throw new BadCredentialsException("Cannot process authentication token");
        }


        int delim = token.indexOf(":");

        if (delim == -1) {
            throw new BadCredentialsException("Invalid authentication token");
        }
        return new String[]{token.substring(0, delim), token.substring(delim + 1)};
    }
}
